package com.platform.modules.mch.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.ValidUtils;
import com.platform.common.utils.mch.HttpUtils;
import com.platform.common.utils.mch.config.MchConfig;
import com.platform.modules.mall.entity.MallGoodsEntity;
import com.platform.modules.mall.service.MallGoodsService;
import com.platform.modules.mch.dto.LLGoodsDto;
import com.platform.modules.mch.dto.MchGoodsNumberLockDto;
import com.platform.modules.mch.entity.MchGoodsExtendEntity;
import com.platform.modules.mch.service.MchGoodsExtendService;
import com.platform.modules.mch.service.MchGoodsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MchGoodsServiceImpl implements MchGoodsService {

    @Resource
    private MallGoodsService mallGoodsService;
    @Resource
    private MchGoodsExtendService goodsExtendService;

    @Override
    public <T> List<T> getListByIds(List<String> ids, MchConfig.Url url, Class<T> tClass) {
        // 单次请求最大查询数量
        int maxCount = 500;
        List<T> records;
        boolean limit = ids.size() > maxCount;
        JSONObject params = new JSONObject();
        params.put("ids", limit?ids.subList(0,maxCount):ids);
        params.put("page", 1);
        params.put("limit", limit?maxCount:ids.size());
        params.put("locationId", MchConfig.getLocationId());
        try {
            records = HttpUtils.sendPost(url.getUrl(), params)
                    .getJSONArray("records")
                    .toJavaList(tClass);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("数据获取失败！");
        }
        if(ids.size() > maxCount){
            records.addAll(getListByIds(ids.subList(maxCount,ids.size()),url,tClass));
        }
        return records;
    }

    // todo risk hch 待优化，需要将html_content字段单独提取出来交由其余线程后台执行同步
    @Override
    public void syncGoods(String categoryId, List<String> ids) {

        // 通过ID查询联联商品
        List<LLGoodsDto> records = this.getListByIds(ids,MchConfig.Url.queryLLGoods,LLGoodsDto.class);

        // 删除的产品进行恢复
        mallGoodsService.undelete(records.parallelStream()
                        .map(x -> x.getGoods().getId())
                        .collect(Collectors.toList()));

        // 保存商品   此处有大量联联属性没使用上
        List<MallGoodsEntity> collect = records.parallelStream()
                .map(x -> {
                    x.getGoods().setCategoryId(categoryId);
                    x.getGoods().setGoodsNumber(null);
                    x.getGoods().setIsDelete(1);
                    x.getGoods().setSellVolume(x.getGoods().getSales()); // 销量
                    return x.getGoods();
                }).collect(Collectors.toList());
        this.batchSave(collect);

        // 保存商品属性
        List<MchGoodsExtendEntity> extendEntityList = records.parallelStream()
                .map(MchGoodsExtendEntity::new).collect(Collectors.toList());
        goodsExtendService.saveOrUpdateBatch(extendEntityList);
    }

    @Override
    public JSONObject list(JSONObject params) {
        try {
            return HttpUtils.sendPost(MchConfig.Url.queryGoods.getUrl(), params);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("数据获取失败！");
        }
    }

    @Override
    public List<MallGoodsEntity> queryGoods(int page, int limit, String locationId) {
        try {
            JSONObject params = new JSONObject();
            params.put("locationId", locationId);
            params.put("page", page);
            params.put("limit", limit);
            JSONObject jsonObject = this.list(params);
            return jsonObject.getJSONArray("records").toJavaList(MallGoodsEntity.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("数据获取失败！");
        }
    }

    @Override
    public boolean batchSave(List<MallGoodsEntity> goodsEntities) {
        return mallGoodsService.saveOrUpdateBatch(goodsEntities);
    }

    @Override
    public MchGoodsNumberLockDto getStock(String goodsId) {
        JSONObject params = new JSONObject();
        params.put("goodsId", goodsId);
        return HttpUtils.sendPost(MchConfig.Url.getStock.getUrl(),params,MchGoodsNumberLockDto.class);
    }

    @Override
    public void lockStock(JSONObject params) {
        ValidUtils.allNotNull(params.get("goodsId"),params.get("number"));
        HttpUtils.sendPost(MchConfig.Url.lockStock.getUrl(),params);
        mallGoodsService.lambdaUpdate()
                .setSql("GOODS_NUMBER = GOODS_NUMBER + "+params.get("number"))
                .eq(MallGoodsEntity::getId,params.get("goodsId"))
                .update();
    }

}
